package com.bjb.vr.remote.handler;

import com.bjb.vr.common.exception.BusinessException;
import com.bjb.vr.common.exception.CommonException;
import com.bjb.vr.common.exception.DaoException;
import com.bjb.vr.common.exception.RpcException;
import com.bjb.vr.common.result.BaseErrorCode;
import com.bjb.vr.common.result.BaseResult;
import com.bjb.vr.common.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 自定义错误异常处理类
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/3/21 14:55
 */
@Slf4j
@ControllerAdvice
public class CustomExceptionHandler {

    /**
     * 其他未知异常处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResult errorHandler(Exception ex) {
        log.error("处理异常信息>>> ", ex);
        return CommonResult.Fail(BaseErrorCode.UNKNOWN_ERROR.getCode(), ex.getMessage());
    }


    /**
     * 业务层处理异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public BaseResult errorBusinessHandler(Exception ex) {
        log.error("业务层处理异常信息>>> ", ex);
        return CommonResult.Fail(BaseErrorCode.UNKNOWN_ERROR.getCode(), ex.getMessage());
    }

    /**
     * 通用处理异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = CommonException.class)
    public BaseResult errorCommonHandler(Exception ex) {
        log.error("通用处理异常信息>>> ", ex);
        return CommonResult.Fail(BaseErrorCode.UNKNOWN_ERROR.getCode(), ex.getMessage());
    }

    /**
     * 数据层处理异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = DaoException.class)
    public BaseResult errorDaoHanlder(Exception ex) {
        log.error("数据层处理异常信息>>> ", ex);
        return CommonResult.Fail(BaseErrorCode.UNKNOWN_ERROR.getCode(), ex.getMessage());
    }

    /**
     * 远程调用层处理异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = RpcException.class)
    public BaseResult errorRpcHandler(Exception ex) {
        log.error("远程调用层处理异常信息>>> ", ex);
        return CommonResult.Fail(BaseErrorCode.UNKNOWN_ERROR.getCode(), ex.getMessage());
    }

    /**
     * 错误请求异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public BaseResult errorRequestBody(Exception ex) {
        log.error("错误请求异常信息>>> ", ex);
        return CommonResult.Fail(BaseErrorCode.BAD_REQUEST.getCode(), ex.getMessage());
    }
}
